package com.svmc.app.task.activity;

import java.util.ArrayList;
import java.util.Calendar;

import luyenlv.pro.screen.base.BaseActivity;
import android.content.Intent;
import android.database.Cursor;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.inputmethod.InputMethodManager;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
import android.widget.Toast;

import com.svmc.app.task.adapter.DbAdapter;
import com.svmc.app.task.alarm.MyAlarmManager;
import com.svmc.app.task.model.TaskModel;
import com.svmc.app.task.tabmanager.TabGroupActivity;
import com.svmc.app.task.utils.CommonDefine;
import com.svmc.app.task.utils.DateUtils;
import com.svmc.app.task.utils.UtilString;
import com.svmc.app.task.view.DateDialog;

public class AddNewTask extends BaseActivity implements OnClickListener,CommonDefine {
	ArrayList<TaskModel> listtask;
	private static String txt_timeReminder = "";
	DateUtils dateUtils = new DateUtils();
	EditText task, note;
	CheckBox cb_isreminder;
	TextView timefinish, timereminder,titleRing,namefilering;
	Calendar c = Calendar.getInstance();
	Calendar c1 = Calendar.getInstance();
	//Spinner choseRingtone;
	RelativeLayout rl_reminder;
	ImageView choseRingtone;
	String pathRing ="default Ring"+":"+R.raw.sound_default;
	public static int isFirstSelectRing =0;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		this.requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(getLayout(R.array.addnew_layout));
		
		
		findViewById(R.id.addnew_img_back).setOnClickListener(this);
		findViewById(R.id.addnew_img_done).setOnClickListener(this);
		findViewById(R.id.addnew_spinner_ringtone).setOnClickListener(this);
		
		titleRing = (TextView)findViewById(R.id.addnew_txt_label_ringtone);
		namefilering =(TextView)findViewById(R.id.addnew_txt_titleRing);
		namefilering.setText(getString(R.string.default_ringtone_label));
		task = (EditText) findViewById(R.id.addnew_edt_newtask);
		note = (EditText) findViewById(R.id.addnew_edt_note);
		cb_isreminder = (CheckBox) findViewById(R.id.addnew_cb_isReminder);
		cb_isreminder.setOnClickListener(this);

		timefinish = (TextView) findViewById(R.id.addnew_txt_timefinish);
		timereminder = (TextView) findViewById(R.id.addnew_txt_timereminder);
		timefinish.setOnClickListener(this);
		timereminder.setOnClickListener(this);
		Log.i("test Strinh date", dateUtils.formatDate(c));
		//choseRingtone = (Spinner) findViewById(R.id.addnew_spinner_ringtone);
		
		rl_reminder = (RelativeLayout) findViewById(R.id.addnew_rl_reminder);
		cb_isreminder.setChecked(false);
		hideViewSetReminder();
		timefinish.setText(dateUtils.formatDateToShow(c));
		//timefinish.setText(dateUtils.getCurrentTime(c));
		txt_timeReminder = dateUtils.formatDateToShow(c);
		timereminder.setText(dateUtils.formatDateToShow(c));
		
		
		
	}
	@Override
	protected void onResume() {
		super.onResume();
		//hideAndShowReminder();
	
		
	}
	@SuppressWarnings("unused")
	@Override
	protected void onSaveInstanceState(Bundle outState) {
		// TODO Auto-generated method stub
		super.onSaveInstanceState(outState);
		//showToast("onsave addnew", 0);
		if(TabGroupActivity.isdestroy==true && TabGroupActivity.isstop==true){
			//showToast("onsave addnew =true", 0);
			TabGroupActivity.stateActivity=ADD_NEW_ACTIVITY;
			TabGroupActivity.isdestroy=false;
			TabGroupActivity.isstop=false;
		}else if (TabGroupActivity.isdestroy=false&&TabGroupActivity.isstop==true) {
			TabGroupActivity.isdestroy=false;
			TabGroupActivity.isstop=false;
		}
		
	}

	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.addnew_img_back:
			//showToast(pathRing, 0);
			finish();
			//finishFromChild(this);
			break;
		case R.id.addnew_img_done:
			if (cb_isreminder.isChecked()) {
				MyAlarmManager alarm = new MyAlarmManager(this);
				int id_alarm = (int) System.currentTimeMillis();
				
			long row = addnewtask(task.getText().toString(), c, REMINDER, c1,note.getText().toString(),id_alarm,pathRing);
			
				if(row>0) {
					alarm.SingleAlarmWithData(c1, id_alarm, row);
					Log.i("ID alarm creat : ",""+ id_alarm);
					InputMethodManager imm = (InputMethodManager)getSystemService(this.INPUT_METHOD_SERVICE);
			        imm.hideSoftInputFromWindow(task.getWindowToken(), 0);
			        imm.hideSoftInputFromWindow(note.getWindowToken(), 0);
			        finish();
			        //finishFromChild(this);
				}else {
					showToast("Add new task not successful", Toast.LENGTH_LONG);
				}
				
				
			} else {
				long row = addnewtask(task.getText().toString(), c, NOT_REMINDER, c1,note.getText().toString(),-1,pathRing);
				if(row>0) {
					InputMethodManager imm = (InputMethodManager)getSystemService(this.INPUT_METHOD_SERVICE);
			        imm.hideSoftInputFromWindow(task.getWindowToken(), 0);
			        imm.hideSoftInputFromWindow(note.getWindowToken(), 0);
			        finish();
			        //finishFromChild(this);
				}else {
					showToast("Add new task not successful", Toast.LENGTH_LONG);
				}
			}
			
			break;
		case R.id.addnew_txt_timefinish:
			TabGroupActivity.isdestroy=false;
			Intent timefinishIntent = new Intent(this, DateDialog.class);
			timefinishIntent.putExtra("send_year", c.get(Calendar.YEAR));
			timefinishIntent.putExtra("send_month", c.get(Calendar.MONTH));
			timefinishIntent.putExtra("send_day", c.get(Calendar.DAY_OF_MONTH));
			timefinishIntent.putExtra("send_hour", c.get(Calendar.HOUR_OF_DAY));
			timefinishIntent.putExtra("send_minute", c.get(Calendar.MINUTE));
			timefinishIntent.putExtra(EDIT_OR_NEW,ACTIVITY_NEW);
			this.getParent().startActivityForResult(timefinishIntent, REQUEST_CODE_TIME_FINISH);
			break;
		case R.id.addnew_txt_timereminder:
			TabGroupActivity.isdestroy=false;
			Intent timeReminderIntent = new Intent(this, DateDialog.class);
			timeReminderIntent.putExtra("send_year", c1.get(Calendar.YEAR));
			timeReminderIntent.putExtra("send_month", c1.get(Calendar.MONTH));
			timeReminderIntent.putExtra("send_day", c1.get(Calendar.DAY_OF_MONTH));
			timeReminderIntent.putExtra("send_hour", c1.get(Calendar.HOUR_OF_DAY));
			timeReminderIntent.putExtra("send_minute", c1.get(Calendar.MINUTE));
			timeReminderIntent.putExtra(EDIT_OR_NEW, ACTIVITY_NEW);
			this.getParent().startActivityForResult(timeReminderIntent, REQUEST_CODE_TIME_REMINDER);
			break;
		case R.id.addnew_cb_isReminder:
			

			if (cb_isreminder.isChecked() == false) {
				hideViewSetReminder();
			} else {
				showViewSetReminder();
				timereminder.setText(txt_timeReminder);
				c1=c;
				isFirstSelectRing = 1;
				//getPathRingtone();
			}

			break;
		case R.id.addnew_spinner_ringtone:
			TabGroupActivity.isdestroy=false;
			Intent ringIntent = new Intent(this, SelectRingtone.class);
			ringIntent.putExtra(EDIT_OR_NEW, ACTIVITY_NEW);
			this.getParent().startActivityForResult(ringIntent, REQUEST_CODE_SELECT_RINGTONE);
			break;
		default:
			break;
		}

	}
	
		

	public void handeonActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);

		int year, month, day, hour, minute;
		switch (requestCode) {

		case REQUEST_CODE_TIME_FINISH:
			if (resultCode == RESULT_OK) {
				try {
					Bundle bundle = data.getExtras();
					year = bundle.getInt("year");
					month = bundle.getInt("month");
					day = bundle.getInt("day");
					hour = bundle.getInt("hour");
					minute = bundle.getInt("minute");
					c = dateUtils.setTime(year, month, day, hour, minute);
					timefinish.setText(dateUtils.formatDateToShow(c));
					txt_timeReminder = dateUtils.formatDateToShow(c);
					
				} catch (NullPointerException e) {

				}

			}
			break;
		case REQUEST_CODE_TIME_REMINDER:
			if (resultCode == RESULT_OK) {
				try {
					Bundle bundle = data.getExtras();
					year = bundle.getInt("year");
					month = bundle.getInt("month");
					day = bundle.getInt("day");
					hour = bundle.getInt("hour");
					minute = bundle.getInt("minute");
					c1 = dateUtils.setTime(year, month, day, hour, minute);
					timereminder.setText(dateUtils.formatDateToShow(c1));
				} catch (NullPointerException e) {

				}

			}
			break;
		case REQUEST_CODE_SELECT_RINGTONE:
			if(resultCode == RESULT_OK){
				try {
					Bundle bundle =data.getExtras();
					String title = bundle.getString("titleRing");
					//pathRing = bundle.getString("pathRing");
					String pathringtone = bundle.getString("pathRing");
					namefilering.setText(title);
					UtilString utils = new UtilString();
					pathRing = utils.formatStringPutData(title, pathringtone);
				} catch (NullPointerException e) {
					namefilering.setText("nullpointer");
				}
				
			}
			break;
		default:
			break;
		}
	}

	/**
	 * add new task 
	 * 
	 * @param tasknote
	 * @param duedate
	 * @param isreminder
	 * @param timereminder
	 */
	public long addnewtask(String tasknote, Calendar duedate, int isreminder,
			Calendar timereminder,String note,int idAlarm,String pathRing) {
		TaskModel task = new TaskModel();
		long row=0;
		DbAdapter db = new DbAdapter(this);
		task.setTask(tasknote);
		task.setIsreminder(isreminder);
		task.setTimefinish(dateUtils.formatDate(duedate));
		task.setNote(note);
		if (isreminder == 1) {

			task.setTimereminder(dateUtils.formatDate(timereminder));
			task.setId_alarm(idAlarm);
			task.setPathRingtone(pathRing);
			row =db.addTask(task);
		} else {
			row= db.addTask(task);
		}
		return row;

	}

	public void showViewSetReminder() {
		rl_reminder.setVisibility(View.VISIBLE);

	}

	public void hideViewSetReminder() {
		rl_reminder.setVisibility(View.GONE);
	}
	Ringtone ring = null;
	
	public void getPathRingtone(){
		/*
		List<String> list = new ArrayList<String>();
		list.add("list 1");
		list.add("list 2");
		list.add("list 3");
		ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,
			android.R.layout.simple_spinner_item, list);
		dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		
		choseRingtone.setAdapter(dataAdapter);
	*/
		
		RingtoneManager mRingtone = new RingtoneManager(this);

		mRingtone.setType(RingtoneManager.TYPE_RINGTONE);
		mRingtone.setIncludeDrm(true);
		Cursor mCursor = mRingtone.getCursor();
		startManagingCursor(mCursor);
		//String test = mCursor.getString(mCursor.getColumnIndexOrThrow(RingtoneManager.EXTRA_RINGTONE_TITLE));
		String[] from = {mCursor.getColumnName(RingtoneManager.TITLE_COLUMN_INDEX)};
		int[] to = {android.R.id.text1};
		SimpleCursorAdapter adapter =
			      new SimpleCursorAdapter(this, android.R.layout.simple_spinner_item, mCursor, from, to );
		adapter.setDropDownViewResource( android.R.layout.simple_spinner_dropdown_item );
		/*	   
		choseRingtone.setAdapter(adapter);
		choseRingtone.setOnItemSelectedListener(new OnItemSelectedListener() {

			@Override
			public void onItemSelected(AdapterView<?> parentView, View view,
					int position, long id) {
				if(ring ==null){
					RingtoneManager r = new RingtoneManager(getApplicationContext());
					ring = r.getRingtone(position);					
					//ring.play();
				}else {
					ring.stop();
					RingtoneManager r = new RingtoneManager(getApplicationContext());
					ring = r.getRingtone(position);					
					ring.play();
				}
				showToast("select : " +position, 0);
			}

			@Override
			public void onNothingSelected(AdapterView<?> arg0) {
				
				
			}
			
		});
		*/
	}
	public void hideAndShowReminder (){
		if (cb_isreminder.isChecked() == false) {
			hideViewSetReminder();
		} else {
			showViewSetReminder();
			timereminder.setText(txt_timeReminder);
			c1=c;
			//isFirstSelectRing = 1;
			//getPathRingtone();
		}
	}

	public void showToast(String text, int type) {
		Toast.makeText(this, text, type).show();
	}
	

	@Override
	public void clearMemory() {

	}
	/**
	 * get all task from database
	 * @return
	 */
	public ArrayList<TaskModel> getAllTask (){
		DbAdapter db = new DbAdapter(this);
		return db.getAllTask();
	}
	@Override
	protected void onStop() {
		// TODO Auto-generated method stub
		super.onStop();
		TabGroupActivity.isstop=true;
	}
	
	@Override
		protected void onDestroy() {
			super.onDestroy();
			TabGroupActivity.isdestroy=true;
			//showToast("add new destroy", 0);
			task=null;
			note = null;
			dateUtils = null;
			cb_isreminder=null;
			timefinish=null;
			timereminder=null;
			titleRing =null;
			namefilering=null;
			choseRingtone=null;
			System.gc();
		}
}
